package com.guo.rabbitmq.api.exchange.direct;

import com.guo.rabbitmq.constant.RabbitMqConstant;
import com.rabbitmq.client.*;

import java.io.IOException;


/**
 * @author guo
 * @date 2021/11/17 18:45 星期三
 **/
public class Consumer4DirectExchange {
    public static void main(String[] args) throws Exception {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(RabbitMqConstant.HOST);
        connectionFactory.setPort(RabbitMqConstant.PORT);
        connectionFactory.setVirtualHost(RabbitMqConstant.VIRTUAL_HOST);

        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();

        String queueName = "test.direct.exchange";
        String exchange = "test.directExchange";
        String routingKey = "test.direct.exchange";

        channel.queueDeclare(queueName,true,false,false,null);
        channel.exchangeDeclare(exchange,"direct",true,false,false,null);
        channel.queueBind(queueName,exchange,routingKey,null);
        channel.basicQos(0,1,false);
        channel.basicConsume(queueName,false,"",
                new DefaultConsumer(channel){
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                        System.out.println("Exchange ：" + envelope.getExchange());
                        System.out.println("RoutingKey : " + envelope.getRoutingKey());
                        System.out.println("DeliveryTag : " + envelope.getDeliveryTag());
                        System.out.println("consumerTag ：" + consumerTag);
                        System.out.println("properties：" + properties.toString());
                        System.out.println("msg ：" + new String(body));
                        System.out.println("==========================华丽的分割线================================");
                        channel.basicAck(envelope.getDeliveryTag(),false);
                    }
                });

//        channel.close();
//        connection.close();


    }
}
